package DataOperator;

import java.io.IOException;
import java.io.RandomAccessFile;

import BufferReader.BufferReader;
import DictData.OxfordWordInfo;
import SearchTree.SearchTreeLoader;
import SimpleDict.DictData;

public class Loader {
	
	SearchTreeLoader catalog = null;
	RandomAccessFile dict = null;
	BufferReader reader = null;
	
	public void Init(String indexFile, String dictFile){
		catalog = new SearchTreeLoader();
		catalog.Import(indexFile);
		try{
			dict = new RandomAccessFile(dictFile, "r");
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public void Release(){
		try {
			dict.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean LoadData(String word){
		if(catalog.Find(word)){
			int offset = catalog.GetOffset();
			int length = catalog.GetLength();
			byte buffer[] = new byte[length];
			try{
				dict.seek(offset);
				dict.read(buffer);
			}
			catch(IOException e){
				e.printStackTrace();
			}
			reader = new BufferReader(buffer);
			return true;
		}
		return false;
	}
	
	public OxfordWordInfo LoadOxfordWordInfo(String word){
		if(LoadData(word)){
			OxfordWordInfo rev = new OxfordWordInfo();
			rev.Read(reader);
			return rev;
		}
		return null;
	}
	
	public DictData LoadSimpleWordInfo(String word){
		if(LoadData(word)){
			DictData rev = new DictData();
			rev.soundOff = reader.ReadInt();
			rev.soundLen = reader.ReadInt();
			rev.content = reader.ReadString();
			return rev;
		}
		return null;
	}
	
	public static void main(String args[]){
		Loader loader = new Loader();
		loader.Init(IDSPackager.IndexFilePath, IDSPackager.DictFilePath);
		DictData info = loader.LoadSimpleWordInfo("frugal");
		info.toString();
	}
}
